package com.xmutca.rabbitmq.demo3;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class ProviderTest {

    public static final String NOMAL_QUENE_NAME = "queue_demo3";
    public static final String AE_QUENE_NAME = "queue_demo3_ae";
    public static final String IP_ADDRESS = "127.0.0.1";
    public static final String EXCHANGE_DEMO_NAME = "exchange_demo3";
    public static final String EXCHANGE_AE_NAME = "exchange_demo3_ae";
    public static final String ROUTING_KEY = "routingkey_demo3";
    public static final String USERNAME = "guest";
    public static final String PASSWORD = "guest";
    public static final int PORT = 5672;

    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 设置rabbitmq的各种信息
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(USERNAME);
        factory.setPassword(PASSWORD);
        factory.setPort(PORT);
        factory.setHost(IP_ADDRESS);

        // 2. 获取连接
        Connection conn = factory.newConnection();

        // 3. 创建通道
        Channel channel = conn.createChannel();

        // 4. 创建一个直连的，持久化的，非自动删除的交换机(假设是一个邮局)
        Map<String, Object> agrs = new HashMap();
        agrs.put("alternate-exchange", EXCHANGE_AE_NAME);

        channel.exchangeDeclare(EXCHANGE_DEMO_NAME, BuiltinExchangeType.DIRECT, true, false, agrs);
        channel.exchangeDeclare(EXCHANGE_AE_NAME, BuiltinExchangeType.FANOUT, true, false, null);

        // 5. 创建一个持久化的，非排他的，非自动删除的队列(目的地)
        channel.queueDeclare(NOMAL_QUENE_NAME, true, false, false, null);
        channel.queueDeclare(AE_QUENE_NAME, true, false, false, null);

        // 6. 将交换机与队列，通过路由key进行绑定(相当于是规划投递路线，从邮局到目的地，此时ROUTING_KEY充当的是目的地)
        channel.queueBind(NOMAL_QUENE_NAME, EXCHANGE_DEMO_NAME, ROUTING_KEY);
        channel.queueBind(AE_QUENE_NAME, EXCHANGE_AE_NAME, "");

        // 7. 发送消息(投递消息给邮局, ROUTING_KEY相当于包裹上的地址)
        String message = "hello world";
        channel.basicPublish(EXCHANGE_DEMO_NAME, ROUTING_KEY + "1", MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());

        // 8. 关闭资源
        channel.close();
        conn.close();
    }
}
